﻿using System;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace StairsModuleAndEdit.StairsEdit.Common
{
	internal class StairsXDataManager
	{
		private static Schema CreateSimpleSchema()
		{
			SchemaBuilder schemaBuilder = new SchemaBuilder(StairsXDataManager.m_Guid);
			schemaBuilder.SetReadAccessLevel((AccessLevel)1);
			schemaBuilder.SetSchemaName(StairsXDataManager.m_sArchStairs);
			schemaBuilder.AddSimpleField(StairsXDataManager.m_sArchStairs, typeof(ElementId));
			return schemaBuilder.Finish();
		}

		private static bool HasSchema(out Schema schema)
		{
			Schema schema2 = Schema.Lookup(StairsXDataManager.m_Guid);
			schema = schema2;
			return schema2 != null;
		}

		public static void WriteArchStairsId(Element element, ElementId ArchStairsId)
		{
			Schema schema = null;
			if (!StairsXDataManager.HasSchema(out schema))
			{
				schema = StairsXDataManager.CreateSimpleSchema();
			}
			if (StairsXDataManager.m_StairsEnt == null)
			{
				StairsXDataManager.m_StairsEnt = new Entity(schema);
			}
			Field field = schema.GetField(StairsXDataManager.m_sArchStairs);
			StairsXDataManager.m_StairsEnt.Set<ElementId>(field, ArchStairsId);
			element.SetEntity(StairsXDataManager.m_StairsEnt);
			StairsXDataManager.m_StairsEnt = null;
		}

		public static bool ReadArchStairsId(Element element, ref ElementId ArchStairsId)
		{
			Schema schema = null;
			if (StairsXDataManager.HasSchema(out schema))
			{
				Entity entity = element.GetEntity(schema);
				if (entity.IsValid())
				{
					Field field = schema.GetField(StairsXDataManager.m_sArchStairs);
					if (field != null)
					{
						ArchStairsId = entity.Get<ElementId>(field);
						return true;
					}
				}
			}
			return false;
		}

		public static bool DeleteArchStairsEntity(Element element)
		{
			Schema schema = null;
			return StairsXDataManager.HasSchema(out schema) && element.DeleteEntity(schema);
		}

		private static Guid m_Guid = new Guid("DA6162EC-6A21-4CD6-BE34-B861F8BB74D3");

		public static string m_sArchStairs = "ArchStairsId";

		public static Entity m_StairsEnt = null;
	}
}
